<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
    <title>商品管理</title>
    <link rel="stylesheet" type="text/css" href="static/admin/layui/css/layui.css"/>
    <link rel="stylesheet" type="text/css" href="static/admin/css/admin.css"/>
    <script>
        function checkPrice(obj) {
            //修复第一个字符是小数点 的情况.
            if (obj.value !== '' && obj.value.substr(0, 1) === '.') {
                obj.value = "";
            }
            //解决 粘贴不生效
            obj.value = obj.value.replace(/^0*(0\.|[1-9])/, '$1');
            //清除“数字”和“.”以外的字符
            obj.value = obj.value.replace(/[^\d.]/g, "");
            //只保留第一个小数点(.)清除多余的
            obj.value = obj.value.replace(/\.{2,}/g, ".");
            obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
            //只能输入两个小数
            obj.value = obj.value.replace(/^(\d+)\.(\d\d).*$/, '$1.$2');
            if (obj.value.indexOf(".") < 0 && obj.value !== "") {//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
                if (obj.value.substr(0, 1) === '0' && obj.value.length === 2) {
                    obj.value = obj.value.substr(1, obj.value.length);
                }
            }
        }
        function checkNum(obj) {
            //解决 粘贴不生效
            obj.value = obj.value.replace(/^0*(0\.|[1-9])/, '$1');
            //清除“数字”和“.”以外的字符
            obj.value = obj.value.replace(/[^\d]/g, "");
            if (obj.value.substr(0, 1) === '0' && obj.value.length === 2) {
                obj.value = obj.value.substr(1, obj.value.length);
            }
        }
    </script>
</head>
<body>
<div class="wrap-container welcome-container">
    <div class="wrap-container clearfix">
        <div class="column-content-detail">
            <div class="layui-form-item">
                <button class="layui-btn layui-btn-sm layui-btn-normal addBtn"><i class="layui-icon">&#xe654;</i>
                </button>
            </div>
            <div class="layui-form" id="table-list">
                <table class="layui-table" lay-even lay-skin="nob">
                    <thead>
                    <tr>
                        <th>商品名称</th>
                        <th>缩略图</th>
                        <th>单价(元)</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody class="table-content"></tbody>
                </table>
            </div>
        </div>
    </div>
    <div id="page"></div>
</div>
<!--商品编辑弹窗-->
<div class="user-edit-popup">
    <form class="layui-form" id="form">
        <input type="hidden" name="id" id="commodity-id">
        <div class="layui-form-item">
            <label class="layui-form-label">商品名称</label>
            <div class="layui-input-inline">
                <input type="text" name="productName" data-name="商品名称" required lay-verify="required"
                       placeholder="请输入商品名称"
                       autocomplete="off" class="required layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品单价</label>
            <div class="layui-input-inline">
                <input type="text" name="productPrice" data-name="商品单价" required lay-verify="required" oninput="checkPrice(this)"
                       placeholder="请输入商品单价" autocomplete="off" class="layui-input required">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品数量</label>
            <div class="layui-input-inline">
                <input type="text" oninput="checkNum(this)"  name="productNum" data-name="商品数量" required lay-verify="required"
                       placeholder="请输入商品数量"
                       autocomplete="off" class="layui-input required">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">缩略图</label>
            <div class="layui-input-inline">
                <!--<input type="file" name="image" class="layui-upload-file thumbnailupload" id="thumbnailupload">-->
                <button type="button" class="layui-btn" id="thumbnailupload">
                    <i class="layui-icon">&#xe67c;</i>上传图片
                </button>
            </div>
        </div>
        <div class="thumbnail-preview">
            <img src="" alt="">
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品图</label>
            <div class="layui-input-inline">
                <button type="button" class="layui-btn" id="goodsimgupload">
                    <i class="layui-icon">&#xe67c;</i>上传图片
                </button>
            </div>
        </div>
        <div class="goodsimg-preview">
            <img src="" alt="">
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品详情</label>
            <div class="layui-input-block">
                <script id="container" name="details" class="required" type="text/plain"></script>
            </div>
        </div>
    </form>
</div>
<script src="static/admin/layui/layui.js" type="text/javascript" charset="utf-8"></script>
<!-- 配置文件 -->
<script type="text/javascript" src="static/admin/lib/ueditor/ueditor.config.js"></script>
<!-- 编辑器源码文件 -->
<script type="text/javascript" src="static/admin/lib/ueditor/ueditor.all.js"></script>
<script src="static/admin/js/baseUrl.js"></script>
<script type="text/javascript">
    // 使用layui
    layui.use(['layer', 'jquery', 'form', 'layedit', 'upload', 'laydate', 'laypage'], function () {

        // <!--实例化富文本编辑器-->
        var ue = UE.getEditor('container', {
            //这里可以选择自己需要的工具按钮名称,此处仅选择如下五个
            toolbars: [
                ['source', '|', 'undo', 'redo', '|',
                    'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
                    'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
                    'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
                    'directionalityltr', 'directionalityrtl', 'indent', '|',
                    'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                    'simpleupload'
                ]
            ],
            initialFrameWidth: '100%',
            initialFrameHeight: '300'
        });

        var layer = layui.layer;
        var $ = layui.jquery;
        var form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
        var upload = layui.upload;
        var laydate = layui.laydate;
        // var laypage = layui.laypage;

        //执行一个laydate实例
        laydate.render({
            elem: '#test1' //指定元素
        });
        // form.render();
        var layedit = layui.layedit;
        var laydesc = layedit.build('desc'); //建立编辑器
        //执行上传实例
        var goodsthumbupload = upload.render({
            elem: '#thumbnailupload' //绑定元素
            , url: baseUrl + '/products/uploadFile' //上传接口
            , field: 'image'
            , done: function (res) {
                //上传完毕回调
                console.log(res);
                var imgUrl = baseUrl+ '/'  + res.data;
                $('.thumbnail-preview').find('img').attr('src', imgUrl)
            }
            , error: function () {
                //请求异常回调
            }
        });
        // 执行上传示例
        var goodsimgupload = upload.render({
            elem: '#goodsimgupload', //绑定元素
            url: baseUrl + '/products/uploadFile', //上传接口
            field: 'image',
            done: function (res) {
                //上传完毕回调
                console.log(res);
                var imgUrl = baseUrl+ '/' + res.data;
                $('.goodsimg-preview').find('img').attr('src', imgUrl)
            }
            , error: function () {
                //请求异常回调
            }
        });

        // 请求参数
        // var data = {
        //     page: 1
        // };


        // 获取数据
        function getList(params) {
            $.ajax({
                url: baseUrl + '/products/selectProductsList',
                // data: params,
                type: 'get',
                dataType: 'json',
                contentType: 'application/json',
                withCredentials: true,
                xhrFields: {withCredentials: true},//加这二行支持ajax跨域，携带凭证
                success: function (data) {
                    // console.log(data);
                    if (data.ret === 200) {
                        var list = data.data;
                        var html = '';
                        for (var item of list) {
                            // console.log(item);
                            html += '<tr>' +
                                '<td class="item-name">' + item.productName + '</td>' +
                                '<td class="item-thumb"><img src="'+ item.thumbnailImage +'" alt=""></td>' +
                                '<td class="item-price">' + item.productPrice + '</td>' +
                                '<td>' +
                                '<div class="layui-inline">' +
                                '<button class="layui-btn layui-btn-sm layui-btn-normal edit-btn" data-id="' + item.id + '">' +
                                '<i class="layui-icon">&#xe642;</i>' +
                                '</button>' +
                                '<button class="layui-btn layui-btn-sm layui-btn-danger del-btn" data-id="' + item.id + '">' +
                                '<i class="layui-icon">&#xe640;</i>' +
                                '</button>' +
                                '</div>' +
                                '</td>' +
                                '</tr>';
                        }
                        $('.table-content').html(html);
                    }else  {
                        if (data.ret == 208) {
                            parent.layer.alert(data.msg, {icon: 0}, function () {
                                parent.location.href = 'login.html'
                            })
                        } else {
                            layer.msg(data.msg, {icon: 0, time: 1000});
                        }
                    }
                },
                error: function () {
                    layer.msg('网络请求错误，请稍后再试', {icon: 0})
                }
            })
        }

        // 初始数据请求
        getList();
        // $('.search').click(function () {
        //     data.key = $('.keywords').val();
        //     // console.log(data);
        //     //发起请求
        //     getList(1, data)
        // });

        // 提交
        function submitFun(submitUrl, editType) {
            var num = 0;
            var str = "";
            $("#form input.required").each(function (n) {
                if ($(this).val() == "") {
                    layer.alert(str += "" + $(this).data("name") + "不能为空！\r\n", {
                        title: '提示',
                        icon: 0,
                    });
                    num++;
                    return false;
                }
            });
            if (num > 0) {
                return false;
            } else {
                var html;
                html = ue.getContent();
                if (html == "" || !html) {
                    layer.alert('请输入商品详情！', {title: '提示', icon: 0})
                } else {
                    var loading = layer.load(1, {shade: [0.3, '#000']});
                    var param = {
                        productName: $('#form').find('input[name=productName]').val(),
                        productPrice: $('#form').find('input[name=productPrice]').val(),
                        productNum: $('#form').find('input[name=productNum]').val(),
                        details: html,
                        productImage: $('#form').find('.goodsimg-preview img').attr('src'),
                        thumbnailImage: $('#form').find('.thumbnail-preview img').attr('src')
                    };
                    type = 'edit' && (param.id = $('#form').find('input[name=id]').val());
                    $.ajax({
                        url: submitUrl,
                        type: 'post',
                        data: JSON.stringify(param),
                        dataType: 'json',
                        contentType: 'application/json',
                        withCredentials: true,
                        xhrFields: {withCredentials: true},//加这二行支持ajax跨域，携带凭证
                        success: function (res) {
                            var tips = '';
                            var icon = 0;
                            if (res.ret == 200) {
                                if(res.data){
                                    (editType == 'add') ? (tips = '添加成功') : (tips = '修改成功');
                                    icon = 1;
                                }else {
                                    (editType == 'add') ? (tips = '添加失败') : (tips = '修改失败');
                                    icon = 0;
                                }
                                layer.msg(tips, {icon: icon, time: 1000}, function () {
                                    icon == 1 && location.reload();//刷新页面
                                });
                            } else {
                                if (data.ret == 208) {
                                    parent.layer.alert(data.msg, {icon: 0}, function () {
                                        parent.location.href = 'login.html'
                                    })
                                } else {
                                    layer.msg(data.msg, {icon: 0, time: 1000});
                                }
                            }
                        },
                        error: function () {
                            layer.msg('网络发生故障，请稍后再试', {icon: 0, time: 1000});
                        },
                        complete: function () {
                            layer.close(loading);
                        }
                    })
                }
            }
        }

        // 关闭
        function clearFun() {
            $("#form input").each(function (n) {
                $(this).val('');
            });
            $("#form").find('img').attr('src', '');
            ue.addListener('ready', function () {
                //默认显示内容
                ue.setContent('');
            });
        }

        // 监听编辑按钮
        $('.table-content').on('click', '.edit-btn', function () {
            // 设置默认值
            var $tar = $(this);
            var id = $tar.data('id');
            $.ajax({
                url: baseUrl + '/products/getProductDetailById',
                data: {
                    id: id
                },
                dataType: 'json',
                contentType: 'application/json',
                withCredentials: true,
                xhrFields: {withCredentials: true},//加这二行支持ajax跨域，携带凭证
                success: function (data) {
                    console.log(data);
                    if (data.ret === 200) {
                        $('#form').find('input[name=id]').val(id);
                        $('#form').find('input[name=productName]').val(data.data.productName);
                        $('#form').find('input[name=productPrice]').val(data.data.productPrice);
                        $('#form').find('input[name=productNum]').val(data.data.productNum);
                        $('#form').find('.thumbnail-preview img').attr('src',data.data.thumbnailImage);
                        $('#form').find('.goodsimg-preview img').attr('src', data.data.productImage);

                        ue.addListener('ready', function () {
                            //默认显示内容
                            ue.setContent(data.data.details);
                        });
                        layer.open({
                            zIndex: 1000,
                            type: 1,
                            content: $('.user-edit-popup'),
                            title: '编辑商品',
                            maxmin: true,
                            shadeClose: true, //点击遮罩关闭层
                            area: '75%',
                            btn: ['提交', '取消'],
                            yes: function (index, layero) {
                                submitFun( baseUrl + '/products/insertOrUpdateProducts', 'edit');
                            },
                            end: function () {
                                clearFun();
                            }

                        })
                    }
                },
                error: function () {
                    layer.msg('网络出现问题，请稍后再试！',{icon: 0})
                }
            })
        });

        // 监听添加按钮
        $('.addBtn').click(function () {
            layer.open({
                zIndex: 1000,
                type: 1,
                content: $('.user-edit-popup'),
                title: '添加商品',
                maxmin: true,
                shadeClose: true, //点击遮罩关闭层
                area: '75%',
                btn: ['提交', '取消'],
                yes: function (index, layero) {
                    submitFun( baseUrl + '/products/insertOrUpdateProducts', 'add');
                },
                end: function () {
                    clearFun();
                }

            })
        });

        // 监听删除按钮
        $('.table-content').on('click', '.del-btn', function () {
            var $tar = $(this);
            layer.confirm('确定删除当前商品吗！', {icon: 5}, function (index) {
                layer.close(index);
                console.log("删除当前商品");
                var id = $tar.data('id');
                // 发起删除请求
                var loading = layer.load(1, {shade: [0.3, '#000']});
                $.ajax({
                    url:  baseUrl + '/products/deleteProductById',
                    type: 'get',
                    data: {id: id},
                    dataType: 'json',
                    contentType: 'application/json',
                    withCredentials: true,
                    xhrFields: {withCredentials: true},//加这二行支持ajax跨域，携带凭证
                    success: function (res) {
                        layer.msg(res.msg, {icon: res.ret== 200 ? 1 : 0, time: 1000}, function () {
                            res.ret == 200 && location.reload();//刷新页面
                        });
                    },
                    error: function () {
                        layer.msg('网络发生故障，请稍后再试', {icon: 0, time: 1000});
                    },
                    complete: function () {
                        layer.close(loading);
                    }
                })
            })
        })


    })
</script>
</body>
</html>
